package com.training.config;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.server.ServerWebExchange;

/**
 * @BelongsProject: environment-supervision
 * @BelongsPackage: com.training.config
 * @Author: Tianyu Han
 * @CreateTime: 2024-05-27  09:34
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Configuration
public class SaTokenConfigure  {

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }




    // 注册 Sa-Token 拦截器，打开注解式鉴权功能
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                // 拦截地址
                .addInclude("/**")    /* 拦截全部path */
                // 开放地址
                .addExclude("/swagger-ui.html")
                .addExclude("/swagger-ui/**")
                .addExclude("/v3/api-docs")
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 登录校验 -- 拦截所有路由，并排除/user/doLogin 用于开放登录
                    SaRouter.match("/**")
                            .notMatch("/admin/login", "/admin/test")
                            .notMatch("/decision/login")
                            .notMatch("/inspector/login")
                            .notMatch("/surveillance/login")
                                    .check(r -> StpUtil.checkLogin());
                    // 权限认证 -- 不同模块, 校验不同权限
//                    SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
//                    SaRouter.match("/decision/**", r -> StpUtil.checkPermission("decision"));
//                    SaRouter.match("/inspector/**", r -> StpUtil.checkPermission("inspector"));
//                    SaRouter.match("/surveillance/**", r -> StpUtil.checkPermission("surveillance"));

                    // 更多匹配 ...  */
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e ->
                {
                    ServerWebExchange exchange = SaReactorSyncHolder.getContext();
                    exchange.getResponse().setStatusCode(HttpStatusCode.valueOf(401));
                    log.error("SaReactorFilter异常", e);
                   return SaResult.error(e.getMessage()).setCode(401);
                });
    }
}
